<?php
namespace app\api\controller\service;

use app\api\model\service\JoinShop;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Loader;

/**
 * 首页接口
 */
class Shop extends Api
{
    protected $noNeedLogin = ['searchShop','shopDetail','getCodeShop','getSampleShop','searchShopGoods'];
    protected $noNeedRight = ['*'];



    /**
     * 申请成为商家
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function apply()
    {
        $uid = $this->auth->id;
        $userInfo = model('app\api\model\service\UserInfo')->where(['user_id'=>$uid])->field('id,is_shop')->find();
        $info = model('app\api\model\service\ApplyShop')->where(['user_id'=>$uid])->find();
        $post = input('post.','','trim,strip_tags,htmlspecialchars,xss_clean');
        $types = input('types','');
        $applyShop = new \app\api\model\service\ApplyShop();
        $post['user_id'] = $uid;
        $post['updatetime'] = time();
        if(in_array($types,['add','edit']))
        {
            $validate = Loader::validate('service.ApplyShop');
            if(!$validate->scene($types)->check($post)){
                $this->error($validate->getError());
            }
        }
        if($types == 'add')
        {
            unset($post['types']);
            $applyShop->data($post)->save();
            $this->success('申请已提交,等待审核');
        }elseif($types == 'edit') {
            unset($post['types']);
            if($userInfo['is_shop'] == 1)
            {
                $post['applytype'] = 1;
            }
            $post['state'] = 0;
            $applyShop->allowField(true)->save($post,['id'=>$info['id']]);
            $this->success('申请已提交,等待审核');
        }
        $this->success('信息返回成功',$info);
    }

    /**
     * 查询商家列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function searchShop()
    {
        $get = input('get.','','trim,strip_tags');
        !$get['city'] && $this->error('城市信息缺失');
        (!$get['lng'] || !$get['lat']) && $this->error('定位信息异常');
        $list = \app\api\model\service\Shop::searchShop($get);
        $this->success('信息列表返回成功',$list);
    }


    public function searchShopGoods()
    {
        $shopId = input('shop_id','');
        $shopGoodsIds = \app\api\model\service\Shop::where('id',$shopId)->value('goods_ids');
        $list = \app\api\model\service\Goods::getNewShopGoods($shopGoodsIds,1);
        $this->success('信息返回成功',$list);
    }

    /**
     * 简单商户列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shopList()
    {
        $uid = $this->auth->id;
        $skillCity = \app\api\model\service\Skill::where('user_id',$uid)->value('city');
        $page = input('page/d',1);
        $limit = 10;
        $list = \app\api\model\service\Shop::where(['state'=>1,'city'=>$skillCity])->field('id,code,logo_image,intro,user_id,name,abbr,leader_name,leader_mobile')->order('weigh desc')->page($page)->limit($limit)->select();
        foreach ($list as &$value)
        {
            $value['followNum'] = \app\api\model\service\Follow::getCount(['follow_id'=>$value['id'],'state'=>1]);
            $value['commentScore'] = \app\api\model\service\Comment::getCommentScore(['shop_id'=>$value['id'],'state'=>1]);
        }
        $this->success('信息返回成功',$list);
    }

    public function getSampleShop()
    {
        $id = input('id/d','');
        $shop = \app\api\model\service\Shop::where(['id'=>$id])->field('id,code,logo_image,intro,user_id,name,abbr,license_image')->find();
        $shop['followNum'] = \app\api\model\service\Follow::getCount(['follow_id'=>$shop['id'],'state'=>1]);
        $shop['commentScore'] = \app\api\model\service\Comment::getCommentScore(['shop_id'=>$shop['id'],'state'=>1]);
        $this->success('信息返回成功',$shop);
    }


    public function shopDetail()
    {
        $id = input('id/d','');
        $page = input('page/d',1);
        $info = \app\api\model\service\Shop::getShopDetail(['id'=>$id,'page'=>$page]);
        $uid = $this->auth->isLogin()?$this->auth->id:'';
        !$info && $this->error('商家信息异常');
        $info['followNum'] = \app\api\model\service\Follow::getCount(['follow_id'=>$info['id'],'state'=>1]);
        $info['commentScore'] = \app\api\model\service\Comment::getCommentScore(['shop_id'=>$info['id'],'state'=>1]);
        $info['followState'] = $uid?\app\api\model\service\Follow::getState(['user_id'=>$uid,'follow_id'=>$id]):0;
        $this->success('信息返回成功',$info);
    }

    /**
     * 商户处理服务人员申请
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function joinShopList()
    {
        $uid = $this->auth->id;
        $shop = \app\api\model\service\Shop::where(['user_id'=>$uid])->field('id,accept_nums,already_accept_nums,service_nums,already_service_nums,percent')->find();
        $type = input('type','');
        if($type == 'check')
        {
            $get = input('get.','');
            ($get['state'] == 1 && $get['percent']>$shop['percent']) && $this->error('订单分成请勿超出商户分成');
            ($get['state'] == 1 && $shop['already_service_nums']>=$shop['service_nums']) && $this->error('商户服务者数量已达到上限');
            $re = \app\api\model\service\JoinShop::check($get);
            !$re && $this->error('审核失败');
            $this->success('已审核');
        }
        $state = input('state/d',0);
        $page = input('page/d','');
        $list = \app\api\model\service\JoinShop::getApplyShop(['shop_id'=>$shop['id'],'state'=>$state,'page'=>$page]);
        $this->success('信息返回成功',$list);
    }

    public function allocationOrder()
    {
        $uid = $this->auth->id;
        $shop_id = \app\api\model\service\Shop::where(['user_id'=>$uid])->value('id');
        $get = input('get.','');
        $get['shop_id'] = $shop_id;
        try{
            \app\api\model\service\Order::allocationOrder($get);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('订单已分配');
    }

    public function getShopSkill()
    {
        $uid = $this->auth->id;
        $shop_id = \app\api\model\service\Shop::where(['user_id'=>$uid])->value('id');
        $id = input('id/d','');
        $orderAddress = \app\api\model\service\OrderAddress::where(['order_id'=>$id])->field('lng,lat')->find();
        $goodsId = \app\api\model\service\Order::where(['id'=>$id])->value('goods_id');
        $page = input('page/d','');
        $where['shop_id'] = $shop_id;
        $where['state'] = 1;
        $where[] =['exp',Db::raw("FIND_IN_SET('$goodsId',goods_ids)")];
        $list = \app\api\model\service\Skill::getShopSkill($where,$page);
        foreach ($list as $key=>$value)
        {
            $list[$key]['distance'] = \addons\service\library\Common::distance($value['lng'],$value['lat'],$orderAddress['lng'],$orderAddress['lat']);
        }
        $this->success('信息返回成功',$list);
    }


    public function getShopSkillInfo()
    {
        $get = input('get.','','trim,strip_tags');
        $uid = $this->auth->id;
        $shopId = \app\api\model\service\Shop::where(['user_id'=>$uid])->value('id');
        $skill = \app\api\model\service\Skill::where(['id'=>$get['id'],'shop_id'=>$shopId])->field('id,ensure_price,is_rest,image,percent,name,sex,city,user_id')->find();
        $get['shop_id'] = $shopId;
        $skill['orderList'] = \app\api\model\service\Order::getShopSkillOrder($get);
        if(isset($get['page']))
        {
            unset($get['page']);
        }
        $skill['skillDetail'] = \app\api\model\service\Skill::skillShopDetail(['shop_id'=>$shopId,'id'=>$skill['id'],'user_id'=>$skill['user_id']]);
        $skill['starttime'] = $get['starttime'] ?? '';
        $skill['endtime'] = $get['endtime'] ?? '';
        $this->success('信息返回成功',$skill);
    }

    /**
     * 商户项目列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shopGoods()
    {
        $uid = $this->auth->id;
        $shop = \app\api\model\service\Shop::where(['user_id'=>$uid])->field('id,to_shop,name,intro,logo_image')->find();
        $page = input('page/d',1);
        $shop_state = input('shop_state/d',0);
        $list = \app\api\model\service\Goods::where(['shop_id'=>$shop['id'],'shop_state'=>$shop_state])->field('id,name,cost_seconds,to_shop,note,image,tag_name,price,shop_state,status')->page($page)->limit(10)->select();
        $data['list'] = $list;
        $data['shop'] = $shop;
        $this->success('信息返回成功',$data);
    }


    /**
     * 商户个人中心
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shopIndex()
    {
        $uid = $this->auth->id;
        $data['userInfo'] = \app\api\model\service\UserInfo::where(['user_id'=>$uid])->field('shop_user_money,money')->find();
        $shopInfo = \app\api\model\service\Shop::where(['user_id'=>$uid])->field('id,ensure_price,category_ids,to_shop,goods_ids,accept_nums,already_accept_nums,already_service_nums,service_nums,name,abbr,code,logo_image')->find();
        $data['skillCount'] = \app\api\model\service\Skill::getCount(['shop_id'=>$shopInfo['id']]);
        $shopInfo['goodsList'] = explode(',',$shopInfo['goods_ids']);
        $data['goodsCount'] = count(\app\api\model\service\Goods::getShopPlatformGoods($shopInfo['goods_ids'],$uid));
        $data['shopInfo'] = $shopInfo;
        $data['shopGoodsCount'] = \app\api\model\service\Goods::getCount(['shop_id'=>$shopInfo['id'],'shop_state'=>1]);
        $data['applyCount'] = \app\api\model\service\JoinShop::getCount(['shop_id'=>$shopInfo['id']]);
        $this->success('信息返回成功',$data);
    }


    /**
     * 商户端首页
     * @return void
     * @throws \think\Exception
     */
    public function shopHome()
    {
        $uid = $this->auth->id;
        $shopId = \app\api\model\service\Shop::where(['user_id'=>$uid])->value('id');
        $get = input('get.','','trim,strip_tags');
        $get['shop_id'] = $shopId;
        //筛选时间,订单数量,订单金额
        $starttime = strtotime(date("Y-m-d",time()));
        $data['dayNum'] = \app\api\model\service\Rebate::getNum(['user_id'=>$uid,'type'=>1,'createtime'=>['>',$starttime]]);
        $data['poolNum'] = \app\api\model\service\Order::getOrderCount(['is_pool'=>1,'status'=>1,'is_service'=>['in',[0,-1]]]);
        $data['dayNewCount'] = \app\api\model\service\Order::getOrderCount(['shop_id'=>$shopId,'createtime'=>['>',$starttime],'is_service'=>['in',[0,-1]]]);
        $data['dayFinishCount'] = \app\api\model\service\Order::getOrderCount(['shop_id'=>$shopId,'status'=>['>',5],'finishtime'=>['>',$starttime],'is_service'=>['in',[0,-1]]]);
        $data['dayDispatchCount'] = \app\api\model\service\Order::getOrderCount(['shop_id'=>$shopId,'status'=>1,'to_shop'=>'door','is_service'=>['in',[0,-1]],'skill_id'=>['null','']]);
        $data['dayServiceList'] = \app\api\model\service\Order::getDayServiceList(['shop_id'=>$shopId,'status'=>['in','1,2,3,4,5'],'is_service'=>['in',[0,-1]]]);
        $data['form'] = \app\api\model\service\Order::getForm($get);
        $this->success('信息返回成功',$data);
    }



    /**
     * 商户下服务者列表
     * @return void
     */
    public function shopSkillList()
    {
        $uid = $this->auth->id;
        $shopId = \app\api\model\service\Shop::where(['user_id'=>$uid])->value('id');
        $page = input('page/d',1);
        $list = \app\api\model\service\Skill::getShopSkillList(['shop_id'=>$shopId],$page);
        $this->success('信息返回成功',$list);
    }


    public function updateShopInfo()
    {
        $uid = $this->auth->id;
        $shop = \app\api\model\service\Shop::where(['user_id'=>$uid])->field('id,withdrawtype,day')->find();
        $type = input('type','','trim,strip_tags');
        if($type == 'update')
        {
            $post = input('post.','','trim,strip_tags,htmlspecialchars,xss_clean');
            model('app\api\model\service\Shop')->allowField('withdrawtype,day')->save($post,['user_id'=>$uid]);
            $this->success('信息已更新');
        }
        $this->success('信息返回成功',$shop);
    }

    public function shopCoupon()
    {
        $uid = $this->auth->id;
        $get = input('get.','','trim,strip_tags');
        $shopId = \app\api\model\service\Shop::where(['user_id'=>$uid])->value('id');
        $get['shop_id'] = $shopId;
        $list = \app\api\model\service\Coupon::getCouponList($get);
        $this->success('信息返回成功',$list);
    }

    public function getCodeShop()
    {
        $code = input('code','');
        $shop = \app\api\model\service\Shop::where(['code'=>$code,'state'=>1])->field('id,name,abbr,intro,logo_image')->find();
        !$shop && $this->error('未获取到相关商户信息');
        $this->success('信息返回成功',$shop);
    }


    public function editCoupon()
    {
        $uid = $this->auth->id;
        $shopId = \app\api\model\service\Shop::where(['user_id'=>$uid])->value('id');
        $types = input('types','');
        if($types == 'add')
        {
            $post = input('post.','','trim,strip_tags,htmlspecialchars,xss_clean');
            $goodsList = \app\api\model\service\Goods::where(['shop_id'=>$shopId])->column('id');
            ($post['type'] == 3 && !in_array($post['goods_id'],$goodsList)) && $this->error('商品信息不符');
            $post['shop_id'] = $shopId;
            $post['state'] = 0;
            $coupon = new \app\api\model\service\Coupon($post);
            $coupon->allowField(true)->save();
            $this->success('信息已提交，等待管理员审核');
        }elseif ($types == 'edit')
        {
            $post = input('post.','','trim,strip_tags,htmlspecialchars,xss_clean');
            $coupon = \app\api\model\service\Coupon::where(['id'=>$post['id'],'shop_id'=>$shopId])->find();
            !$coupon && $this->error('优惠券信息异常');
            $coupon = new \app\api\model\service\Coupon();
            $post['is_check'] = 0;
            $coupon->allowField(true)->save($post,['id'=>$post['id']]);
            $this->success('已提交,等待管理员审核');
        }elseif ($types == 'info')
        {
            $id = input('id/d','');
            $coupon = \app\api\model\service\Coupon::where(['id'=>$id,'shop_id'=>$shopId])->find();
            !$coupon && $this->error('优惠券信息异常');
            $this->success('信息返回成功',$coupon);
        }
        $this->error('接口信息异常');
    }

}
